package com.zhouyu.paydemo.unipay.qrcode.ZS;

import com.zhouyu.paydemo.unipay.qrcode.DemoBase;
import com.zhouyu.paydemo.unipay.sdk.QrcService;
import com.zhouyu.paydemo.unipay.sdk.SDKConfig;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 用途：订单推送<br>
 * 日期： 2017-12<br>
 * 声明：以下代码只是为了方便商户测试而提供的样例代码，商户可以根据自己需要，按照技术文档编写。该代码仅供参考，不提供编码，性能，规范性等方面的保障<br>
 */
@Slf4j
public class OrderPush extends HttpServlet{

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String acqCode = req.getParameter("acqCode");
		String orderNo = req.getParameter("orderNo");
		String orderTime = req.getParameter("orderTime");
		String orderType = req.getParameter("orderType");
		String txnAmt = req.getParameter("txnAmt");

		String name = req.getParameter("name");
		String merCatCode = req.getParameter("merCatCode");
		String id = req.getParameter("id");
		String backUrl = req.getParameter("backUrl");
		String frontUrl = req.getParameter("frontUrl");
		String frontFailUrl = req.getParameter("frontFailUrl");
		String paymentValidTime = req.getParameter("paymentValidTime");
		String customerIp = req.getParameter("customerIp");
		
		Map<String, String> contentData = new HashMap<String, String>();

		contentData.put("version", "1.0.0");
		contentData.put("reqType", "0630001903");
		contentData.put("acqCode", acqCode); 
		contentData.put("orderNo", orderNo); 
		contentData.put("orderTime", orderTime); 
		contentData.put("orderType", orderType);
		contentData.put("paymentValidTime", paymentValidTime); //支付有效时间
		contentData.put("orderDesc", "订单描述"); //订单描述
		
		contentData.put("customerIp", customerIp); //持卡人IP，取公网ip
		contentData.put("backUrl", backUrl);//收款通知接收地址
		contentData.put("areaInfo", "1562900");//地区信息
		contentData.put("txnAmt", txnAmt); //金额

        Map<String, String> payeeInfoMap = new HashMap<String, String>(); 
		payeeInfoMap.put("name", name);
		payeeInfoMap.put("id", id);
		payeeInfoMap.put("merCatCode", merCatCode);// 目前不校验
		payeeInfoMap.put("termId", "49000002");

		//敏感信息不加密使用DemoBase.getPayeeInfo方法
		contentData.put("payeeInfo", DemoBase.getPayeeInfo(payeeInfoMap, DemoBase.encoding));
		
		//如果对机构号issCode 配置了敏感信息加密，必须1.送encryptCertId 2.对payerInfo，payeeInfo的值整体加密
		//目前二维码系统要求所有接入均采用加密方式，使用正式机构号测试的时候参考如下方法上送
		//contentData.put("payeeInfo", DemoBase.getPayeeInfoWithEncrpyt(payeeInfoMap,"UTF-8"));
		//contentData.put("encryptCertId", QrcService.getEncryptCertId());

		//以下字段为选送字段
		contentData.put("frontUrl", frontUrl); //前台通知地址
		contentData.put("frontFailUrl", frontFailUrl); //失败交易前台通知地址
		contentData.put("merTransIndex", "喵？" + DemoBase.getCurrentTime()); //商户交易索引
		contentData.put("currencyCode", "156"); //币种，境内机构仅支持156
		contentData.put("reqReserved", "{\"a\":\"b\",\"c\":\"d\"}"+DemoBase.getCurrentTime()); //请求方自定义域
		
		//TODO 测完删掉= =
		contentData.put("orderTimeOut", "20191212000000"); //必送你大爷
		
		//终端信息，子域定义看规范
        Map<String, String> termInfoMap = new HashMap<String, String>(); 
        termInfoMap.put("longitude", "121.483527");
        termInfoMap.put("latitude", "+31.221345");
        termInfoMap.put("networkLicense", "P3100");
        termInfoMap.put("deviceType", "05");
        termInfoMap.put("serialNum", "什么可以中文吗？");
        termInfoMap.put("appVersion", "1.0.0   ");
		contentData.put("termInfo", DemoBase.formInfoBase64(termInfoMap, DemoBase.encoding)); 
		
		Map<String, String> reqData = QrcService.sign(contentData,DemoBase.encoding);			 //报文中certId,signature的值是在signData方法中获取并自动赋值的，只要证书配置正确即可。
		String requestUrl = SDKConfig.getConfig().getQrcB2cMerBackTransUrl();
		Map<String, String> rspData = QrcService.post(reqData,requestUrl,DemoBase.encoding);  //发送请求报文并接受同步应答（默认连接超时时间30秒，读取返回结果超时时间30秒）;这里调用signData之后，调用submitUrl之前不能对submitFromData中的键值对做任何修改，如果修改会导致验签不通过

		if(!rspData.isEmpty()){
			if(QrcService.validate(rspData, DemoBase.encoding)){
				log.info("验证签名成功");
				String respCode = rspData.get("respCode") ;
				if(("00").equals(respCode)){

				}else{
					//其他应答码为失败请排查原因
					//TODO
				}
			}else{
				log.error("验证签名失败");
				//TODO 检查验证签名失败的原因
			}
		}else{
			//未返回正确的http状态
			log.error("未获取到返回报文或返回http状态码非200");
		}
		String reqMessage = DemoBase.genHtmlResult(reqData);
		String rspMessage = DemoBase.genHtmlResult(rspData);
		resp.getWriter().write("</br>请求报文:<br/>"+reqMessage+"<br/>" + "应答报文:</br>"+rspMessage+"");
	}
}
